package database

import (
	"fmt"
	"log"

	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"pets.ser163.cn/config"

	"gorm.io/driver/mysql"
	"gorm.io/driver/postgres"
)

var DB *gorm.DB

func InitDatabase() {
	var err error
	dbConfig := config.ConfigInstance.Database
	switch dbConfig.Type {
	case "sqlite":
		DB, err = gorm.Open(sqlite.Open(dbConfig.SQLite.Path), &gorm.Config{})
	case "mysql":
		dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
			dbConfig.MySQL.User, dbConfig.MySQL.Password, dbConfig.MySQL.Host, dbConfig.MySQL.Port, dbConfig.MySQL.Name)
		DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	case "postgres":
		dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%d sslmode=%s",
			dbConfig.Postgres.Host, dbConfig.Postgres.User, dbConfig.Postgres.Password, dbConfig.Postgres.Name, dbConfig.Postgres.Port, dbConfig.Postgres.SSLMode)
		DB, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})
	default:
		log.Fatalf("Unsupported database type: %s", dbConfig.Type)
	}

	if err != nil {
		log.Fatalf("failed to connect to database: %v", err)
	}
}
